package com.itwn.comic.utils;

import com.itwn.comic.vo.JwtInfo;
import io.jsonwebtoken.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

public class JwtUtil {
    private static Properties properties ;
    static {
        properties = new Properties();
        InputStream in = JwtUtil.class.getClassLoader().getResourceAsStream("jwt.properties");
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String creatToken(JwtInfo jwtInfo){
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.setHeaderParam("alg",properties.getProperty("alg"));
        jwtBuilder.setHeaderParam("typ",properties.getProperty("typ"));
        Long EXPIRE_TIME=Long.parseLong(properties.getProperty("expiration"));
        jwtBuilder.setIssuer(properties.getProperty("issuer"));
        jwtBuilder.setSubject(properties.getProperty("suject"));
        jwtBuilder.setExpiration(new Date(System.currentTimeMillis()+EXPIRE_TIME));
        jwtBuilder.claim("userCode", jwtInfo.getUserCode());
        jwtBuilder.claim("userName", jwtInfo.getUserName());
        jwtBuilder.signWith(SignatureAlgorithm.HS256,properties.getProperty("secret"));
        String compact = jwtBuilder.compact();
        return compact;
    }
    public static String parseToken(String token){
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(properties.getProperty("secret")).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        String userName = (String) body.get("userName");
        return userName;
    }
}
